<?php
namespace Home\Controller;
use Think\Controller;
class InformationController extends BackController {
	public function index(){
		$user = M('user')->where('pwdid=3')->select();
		$this->assign('sc_user',$user);
		
		$sc_student = M('sc_student');
		$where="";
		if((session('qe_user')['xid']!=0) and (session('qe_user')['pwdid']!=7)){
			$where['scid'] = array('eq',session('qe_user')['id'],'and');
			$where['xid'] = array('eq',session('qe_user')['xid'],'and');
		}elseif((session('qe_user')['xid']!=0) and (session('qe_user')['pwdid']==7)){
			$where['xid'] = array('eq',session('qe_user')['xid'],'and');
		}
		$scid = I('get.scid',0,'int');
		$date = I('get.date','','addslashes');
		if($scid != 0){
			$where['scid'] = array('eq',$scid,'and');
			$this->assign('scid',$scid);
		}
		if($date != ''){
			$where['news_time'] = array('eq',$date,'and');
			$this->assign('date',$date);
		}
		$count      = $sc_student->where($where)->count();// 查询满足要求的总记录数
		$Page       = new \Think\Page($count,$this->all_count(1));// 实例化分页类 传入总记录数和每页显示的记录数(25)
		$show       = $Page->show();// 分页显示输出// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
		$sc_data = $sc_student->where($where)->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
		foreach($sc_data as $k=>$v){
			 $sc_data[$k]['sc_name'] = $this->username($v['scid']);
			 $sc_data[$k]['am_name'] = $this->basname($v['am_id']);
		}
		$this->assign('sc_data',$sc_data);
		$this->assign('page',$show);
		$this->assign('count',$count);
		$this->display();
	}
	public function otherkey(){
	    return $array = array(
	        '0'=>0,//默认0
	        '10'=>45,//户外邀约-课程顾问
	        '11'=>46,//户外邀约-市场专员
	        '12'=>47,//户外邀约-市场兼职
	        '13'=>48,//户外邀约-市场兼职2
	        '14'=>49,//户外邀约-市场兼职3
	        '15'=>50,//户外邀约-市场兼职4
	        '16'=>51,//户外邀约-市场兼职5
	        '17'=>11,//数据库
	        '18'=>12,//Walk in
	        '19'=>35,//Call in
	        '20'=>36,//品牌活动
	        '21'=>52,//异业合作1
	        '22'=>53,//异业合作2
	        '23'=>54,//异业合作3
	        '24'=>55,//异业合作4
	        '25'=>56,//异业合作5
	        '26'=>38,//大众点评
	        '27'=>39,//官网
	        '28'=>40,//微信公众号
	        '29'=>41,//微博
	        '30'=>42,//远播网
	        '31'=>43,//今日头条
	        '32'=>44,//微信朋友圈广告
	        '33'=>10,//销售转介绍
	        '34'=>37,//教师转介绍
	        '35'=>80,//入园讲座
	        '36'=>81,//学校渠道
        );
    }
	public function import() {
		if (IS_POST) {
			$import_user = array();
				//取得成功上传的文件信息
				//$uploadList = $upload -> getUploadFileInfo();
				Vendor('Excel.PHPExcel');
				//导入thinkphp第三方类库
				$import = M('import');
				$import_file = $import->where('start=0 and time='.date('Ymd').' and scid='.session('qe_user')['id'])->order('id desc')->field('link')->find();
				$otherkey = $this->otherkey();
				if($import_file){
					$objPHPExcel = \PHPExcel_IOFactory::load(dirname(dirname(dirname(dirname(__FILE__)))).$import_file['link']);
					//$objPHPExcel = \PHPExcel_IOFactory::load('Uploads/Download/Org/2014-12/547e87ac4b0bf.xls');
					$sheetData = $objPHPExcel -> getActiveSheet() -> toArray(null, true, true, true);
					$model = M("sc_student");
					for ($i = 3; $i <= count($sheetData); $i++) {
						$student['name'] = $sheetData[$i]["B"]?$sheetData[$i]["B"]:"小朋友";
						if(preg_match("/^\d{1,11}$/", $sheetData[$i]["C"])){
							$student['phone'] = $sheetData[$i]["C"];
						}else{
							$student['phone'] = 0; 
						}
						$student['am_id'] = $otherkey[$sheetData[$i]["D"]?$sheetData[$i]["D"]:0];
						$student['sex'] = $sheetData[$i]["E"]?$sheetData[$i]["E"]:0;
						 if(date('Y/m/d',strtotime($sheetData[$i]["F"])) == $sheetData[$i]["F"]){
							 $student['birth_date'] = $sheetData[$i]["F"];
						 }else{
							$student['birth_date'] = date("Y-m-d"); 
						 }
						$student['school'] = $sheetData[$i]["G"]?$sheetData[$i]["G"]:0;
						$student['akey_id'] = $sheetData[$i]["H"]?$sheetData[$i]["H"]:0;
						$student['xid'] = session('qe_user')['xid']?session('qe_user')['xid']:0;
						$student['scid'] = session('qe_user')['id']?session('qe_user')['id']:0;
						$student['xsid'] = session('qe_user')['id']?session('qe_user')['id']:0;
						$student['dt_id'] = 0;
						$student['up'] = 0;
						$student['class_id'] = 0;
						$student['state_id'] = 0;
						$student['news_time'] = date("Y-m-d");
						if($model->where('phone='.$student['phone'])->find()){
							M('cf_student') -> add($student);
						}else{
							$student['student_id'] = date("Ymd").rand(00000000,99999999).$i;
							$model -> add($student);
							$student_show = $model->where('phone='.$student['phone'])->find();
							$record['xsid'] = session('qe_user')['id']?session('qe_user')['id']:0;
							$record['sid'] = $student_show['id'];
							$record['content'] = $sheetData[$i]["I"]?$sheetData[$i]["I"]:0;
							$record['start_time'] = date("Y-m-d"); 
							if($record['content']!=0){
								M('record')->add($record);
							}
						}
					}
					$data['start'] = 1;
					if($import->where('link="'.$import_file['link'].'"')->save($data)!==false){
						$this -> success('导入成功！',U('Information/index'));	
					}
				}else{
					$this -> error('请重新上传文件！',U('Information/import'));	
				}
		} else {
			$qe_user = session('qe_user');
			$this->assign('id',$qe_user['id']);
			$this -> display();
		}
	}
	public function addstudent(){
        if(IS_POST) {
            //通过D实例化模型类
            $_POST['student_id'] = date("Ymd").rand(000000000,999999999);
            $_POST['news_time'] = date("Y-m-d");
            $phone = I('post.phone','','addslashes');
            $student = M('sc_student');
            $where['xsid'] = array('eq',I('post.xsid','','int'),'and');
            $where['state_id']  = array('not in',array('9','13'),'and');
            $all_count = $this->all_count(2);
            $count = $student->where($where)->count();
            if($count<$all_count){
                $student_show = $student->where('phone='.$phone)->find();
                $data['xsid'] = I('post.xsid','','int');
                $data['dt_id'] = 0;
                $data['edit_time'] = date("Y-m-d H:i:s");
                if($student_show){
                    if($student_show['up']==1){
                        //已报名
                        if($this->errors($student_show['id'],$student_show['xid'],$student_show['xsid'],'该学生已报名')){
                            $this->error('该学生已报名',U('Customer/studenterrors'));
                        }
                    }else{
                        //未报名
                        if(($student_show['dt_id']==1) and ($student_show['xid']==session('qe_user')['xid'])){
                            //在本校区资源池
                            if($student->where('phone='.$phone)->save($data) !== false) {
                                $this->errors($student_show['id'],$student_show['xid'],$student_show['xsid'],'资源池抽取');
                                $this->success('资源池抽取客户成功',U('Customer/CustomerList'));
                            }else {
                                $this->error('资源池抽取客户失败',U('Customer/CustomerList'));
                            }
                        }elseif(($student_show['dt_id']==0) and ($student_show['xid']==session('qe_user')['xid'])){
                            //不在本校区资源池,检查最新沟通记录日期
                            $record = M('record')->where('sid='.$student_show['id'])->order('start_time desc')->find();
                            $start_time = date("Y-m-d", strtotime("+1 months", strtotime($record['start_time'])));
                            $news_time = date("Y-m-d");
                            if($start_time<$news_time){
                                //超出1个月
                                if($student->where('phone='.$phone)->save($data) !== false) {
                                    $this->errors($student_show['id'],$student_show['xid'],$student_show['xsid'],'销售名单');
                                    $this->success('销售名单抽取成功',U('Customer/CustomerList'));
                                }else {
                                    $this->error('销售名单失败',U('Customer/CustomerList'));
                                }
                            }else{
                                //沟通日期未超出一个月
                                if($this->errors($student_show['id'],$student_show['xid'],$student_show['xsid'],'在沟通时间以内')){
                                    $this->error('在沟通时间以内，无法抽取',U('Customer/studenterrors'));
                                }
                            }
                        }elseif(($student_show['dt_id']==1) and ($student_show['xid']!=session('qe_user')['xid'])){
                            //在跨校区资源池
                            if($this->errors($student_show['id'],$student_show['xid'],$student_show['xsid'],'跨校区资源池')){
                                $this->error('跨校区资源池内，无法抽取',U('Customer/studenterrors'));
                            }
                        }elseif(($student_show['dt_id']==0) and ($student_show['xid']!=session('qe_user')['xid'])){
                            //不在跨校区资源池
                            if($this->errors($student_show['id'],$student_show['xid'],$student_show['xsid'],'跨校区销售名单')){
                                $this->error('跨校区客户名单下，无法抽取',U('Customer/studenterrors'));
                            }
                        }
                    }
                }else{
                    if($student->create()){
                        if($student->add($_POST)) {
                            $this->success('新增成功',U('Customer/CustomerList'));
                        }else {
                            $this->error('新增失败',U('Customer/CustomerList'));
                        }
                    }
                }
            }else{
                $this->error('跟踪客户已达上限!',U('Customer/CustomerList'));
            }
        }else {
            $campus = M('other')->select();
            $this->assign('campus',$campus);
            $this->display();
        }
    }
	//新增客户
    public function adddata(){
        if (IS_POST) {
            $import_user = array();
            //取得成功上传的文件信息
            //$uploadList = $upload -> getUploadFileInfo();
            //导入thinkphp第三方类库
                $sheetData[0] = I();
                //$objPHPExcel = \PHPExcel_IOFactory::load('Uploads/Download/Org/2014-12/547e87ac4b0bf.xls');
                $model = M("sc_student");
                for ($i = 0; $i <= count($sheetData); $i++) {
                    $student['name'] = $sheetData[$i]["name"]?$sheetData[$i]["name"]:"小朋友";
                    if(preg_match("/^\d{1,11}$/", $sheetData[$i]["phone"])){
                        $student['phone'] = $sheetData[$i]["phone"];
                    }else{
                        $student['phone'] = 0;
                    }
                    $student['am_id'] = $sheetData[$i]["am_id"]?$sheetData[$i]["am_id"]:0;
                    $student['sex'] = $sheetData[$i]["sex"]?$sheetData[$i]["sex"]:0;
                    if($sheetData[$i]["birth_date"]){
                        $student['birth_date'] = $sheetData[$i]["birth_date"];
                    }else{
                        $student['birth_date'] = date("Y-m-d");
                    }
                    $student['school'] = $sheetData[$i]["school"]?$sheetData[$i]["school"]:0;
                    $student['akey_id'] = $sheetData[$i]["akey_id"]?$sheetData[$i]["akey_id"]:0;
                    $student['xid'] = session('qe_user')['xid']?session('qe_user')['xid']:0;
                    $student['scid'] = session('qe_user')['id']?session('qe_user')['id']:0;
                    $student['xsid'] = session('qe_user')['id']?session('qe_user')['id']:0;
                    $student['dt_id'] = 0;
                    $student['up'] = 0;
                    $student['class_id'] = 0;
                    $student['state_id'] = 0;
                    $student['news_time'] = date("Y-m-d");
                    $add = '';
                    if($model->where('phone='.$student['phone'])->find()){
                        $add = M('cf_student') -> add($student);
                    }else{
                        $student['student_id'] = date("Ymd").rand(00000000,99999999).$i;
                        $model -> add($student);
                        $student_show = $model->where('phone='.$student['phone'])->find();
                        $record['xsid'] = session('qe_user')['id']?session('qe_user')['id']:0;
                        $record['sid'] = $student_show['id'];
                        $record['content'] = $sheetData[$i]["content"]?$sheetData[$i]["content"]:0;
                        $record['start_time'] = date("Y-m-d");
                        if($record['content']!=0){
                            $add = M('record')->add($record);
                        }
                    }
                    $this->success('新增成功',U('Customer/CustomerList'));die;
                }
        } else {
            $qe_user = session('qe_user');
            $this->assign('id',$qe_user['id']);
            $this -> display();
        }
    }
	public function Export(){
		if(IS_POST){
		Vendor('Excel.PHPExcel');
		//导入thinkphp第三方类库
		$student = M('cf_student');
		if((session('qe_user')['xid']!=0) and (session('qe_user')['pwdid']!=7)){
			$where['scid'] = array('eq',session('qe_user')['id'],'and');
			$where['xid'] = array('eq',session('qe_user')['xid'],'and');
			$where['news_time'] = array('eq',date('Y-m-d'),'and');
		}elseif((session('qe_user')['xid']!=0) and (session('qe_user')['pwdid']==7)){
			$where['xid'] = array('eq',session('qe_user')['xid'],'and');
			$where['news_time'] = array('eq',date('Y-m-d'),'and');
		}else{
			$xid = I('post.xid');
			if($xid){
				$where['xid'] = array('eq',$xid,'and');
			}
			$news_time = I('post.news_time');
			if($news_time){
				$where['news_time'] = array('eq',$news_time,'and');
			}
		}
		$data = $student->where($where)->select();
		 //实例化
		 $objPHPExcel = new \PHPExcel();
		 /*右键属性所显示的信息*/
		  $objPHPExcel->getProperties()->setCreator("zxf")  //作者
			   ->setLastModifiedBy("zxf")  //最后一次保存者
			   ->setTitle('数据EXCEL导出')  //标题
			   ->setSubject('数据EXCEL导出') //主题
			   ->setDescription('导出数据')  //描述
			   ->setKeywords("excel")   //标记
			   ->setCategory("result file");  //类别
		 
		 
		 //设置当前的表格 
		 $objPHPExcel->setActiveSheetIndex(0);
		 // 设置表格第一行显示内容
		 $objPHPExcel->getActiveSheet()
		  ->setCellValue('A1', '姓名')
		  ->setCellValue('B1', '手机')
			->setCellValue('C1', '渠道来源')
			->setCellValue('D1', '性别')
			->setCellValue('E1', '导入日期')
			->setCellValue('F1', '校区');
		 $key = 1;
		 /*以下就是对处理Excel里的数据，横着取数据*/
		 foreach($data as $v){
		 $xname = $this->basname($v['xid']);
		 //设置循环从第二行开始
		 $key++;
		  $objPHPExcel->getActiveSheet()
		 
			 //Excel的第A列，name是你查出数组的键值字段，下面以此类推
			 ->setCellValue('A'.$key, $v['name'])
			 ->setCellValue('B'.$key, $v['phone'])
			 ->setCellValue('C'.$key, $v['am_id'])
			 ->setCellValue('D'.$key, $v['sex'])
			 ->setCellValue('E'.$key, $v['news_time'])
			 ->setCellValue('F'.$key, $xname);
		 
		 }
		 //设置当前的表格 
		 $objPHPExcel->setActiveSheetIndex(0);
		  header('Content-Type: application/vnd.ms-excel'); //文件类型
		  header('Content-Disposition: attachment;filename="学生信息.xls"'); //文件名
		  header('Cache-Control: max-age=0');
		  header('Content-Type: text/html; charset=utf-8'); //编码
		  $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');  //excel 2003
		  $objWriter->save('php://output'); 
		  exit;
			}
	}
	public function upload(){
		$id = I('post.id',0,'int'); 
		$root_path = dirname(dirname(dirname(dirname(__FILE__))));
		//echo $root_path;exit;
		$filename = 'resume'.$id;  
		if(empty($filename)){  
			
				echo  2;
				exit; 
		}  
		$img_path = '/files/resume/'.date('Ymd').'/';  
		$destination_dir = $root_path.$img_path;  
		
		if(!is_uploaded_file($_FILES[$filename]['tmp_name'])){
				echo json_encode("请选择你想要上传的图片");  
				exit;  
		}  
				$files = $_FILES[$filename];      
				if(!file_exists($destination_dir)) {
						if(!mkdir($destination_dir,0777,true)) {  
								echo "创建目录 {".$destination_dir."} 失败<可能是权限问题>";  
								exit;  
						}  
				}   
				$type = pathinfo($files['name']);  
				$type = strtolower($type["extension"]);  
				$type = ".".$type;  
				$new_name = date('YmdHis').$type;  
				$img_relat_path = $img_path.$new_name;  
				$img_abs_path = $destination_dir.$new_name;    
			
				if(!move_uploaded_file ($files['tmp_name'], $img_abs_path)) {
						echo 3;   
						exit;  
				}else{
					$import = M('import');
					$data['link'] = $img_relat_path;
					$data['scid'] = $id;
					$data['start'] = 0;
					$data['time'] = date('Ymd');
					$import->create();
					$import->add($data);
					echo 1;exit;
				}
		}
		public function chongtu(){
			$user = M('user')->where('pwdid=3')->select();
			$this->assign('sc_user',$user);
			
			$sc_student = M('cf_student');
			$where="";
			if((session('qe_user')['xid']!=0) and (session('qe_user')['pwdid']!=7)){
				$where['scid'] = array('eq',session('qe_user')['id'],'and');
				$where['xid'] = array('eq',session('qe_user')['xid'],'and');
				$where['news_time'] = array('eq',date('Y-m-d'),'and');
			}elseif((session('qe_user')['xid']!=0) and (session('qe_user')['pwdid']==7)){
				$where['xid'] = array('eq',session('qe_user')['xid'],'and');
				$where['news_time'] = array('eq',date('Y-m-d'),'and');
			}
			$scid = I('get.scid',0,'int');
			$date = I('get.date','','addslashes');
			if($scid != 0){
				$where['scid'] = array('eq',$scid,'and');
				$this->assign('scid',$scid);
			}
			if($date != ''){
				$where['news_time'] = array('eq',$date,'and');
				$this->assign('date',$date);
			}
			$count      = $sc_student->where($where)->count();// 查询满足要求的总记录数
			$Page       = new \Think\Page($count,$this->all_count(1));// 实例化分页类 传入总记录数和每页显示的记录数(25)
			$show       = $Page->show();// 分页显示输出// 进行分页数据查询 注意limit方法的参数要使用Page类的属性
			$sc_data = $sc_student->where($where)->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
			foreach($sc_data as $k=>$v){
				$sc_data[$k]['sc_name'] = $this->username($v['scid']);
				$sc_data[$k]['am_name'] = $this->basname($v['am_id']);
			}
			$other_data = M('other')->where('pid=1')->select();
			$this->assign('other_data',$other_data);
			$this->assign('sc_data',$sc_data);
			$this->assign('page',$show);
			$this->assign('count',$count);
			$this->display();
		}
}